package com.yoomiito.app.utils

import android.app.Dialog
import com.yoomiito.app.base.App
import org.greenrobot.eventbus.EventBus

/**
 * 显示规则
 *
 * 弹窗优先级
-版本更新
· 未登录状态弹出
· 已登录状态弹出
· 未登录后操作登录，不弹出
· 已登录后退出登录，不弹出

-新人免单
· 未登录状态不弹出
· 已登录状态弹出
· 未登录后操作登录，弹出
· 已登录后退出登录，不弹出

-配置弹窗
· 未登录状态弹出
· 已登录状态弹出
· 未登录后操作登录，不弹出
· 已登录后退出登录，不弹出

-剪切板搜索
· 只要剪切板有新内容（即本次内容与上一次内容不同），不管登录状态，都弹出
 */
class DialogManager {
    val UPDATE_APK = "download"
    val FREEORDER = "free_order"
    val SYSTEMDIALOG = "system_dialog"
    val SEARCHDIALOG = "search_dialog"
    val PUSHDIALOG = "push_dialog"
    var stopShow = false
    val dialogMap = hashMapOf<String, Dialog?>()
    val showFlag = hashMapOf(PUSHDIALOG to false,UPDATE_APK to false,FREEORDER to false,SYSTEMDIALOG to false,SEARCHDIALOG to false)
    private val keys = listOf(PUSHDIALOG,UPDATE_APK, FREEORDER, SYSTEMDIALOG, SEARCHDIALOG)
    companion object{
        val mInstance by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED){
            DialogManager()
        }
    }

    private fun addShowFlag(key: String) {
        L.i("弹窗管理   添加次数：$key")
        showFlag[key] = true
        if (App.mAppConfig.isLogin) {
            if (showFlag[UPDATE_APK]!! &&showFlag[SYSTEMDIALOG]!!&&showFlag[FREEORDER]!!){
                notifyShowDialog()
            }
        }else{
            if (showFlag[UPDATE_APK]!! &&showFlag[SYSTEMDIALOG]!!){
                notifyShowDialog()
            }
        }
    }

    fun showDialogAgain(key:String){
        showFlag[key] = false
    }

    private fun notifyShowDialog(){
        val eventMessage = EventMessage()
        eventMessage.eventType = AllCode.SHOW_DIALOG
        EventBus.getDefault().post(eventMessage)
    }

    fun addManager(key: String, value: Dialog?) {
        L.i("弹窗管理   添加key：$key   $value")
        dialogMap[key] = value
        addShowFlag(key)
    }

    private fun removeFromManager(key: String) {
        dialogMap.remove(key)
    }

    fun show() {
        for (key in keys) {
            var dialog = dialogMap[key]
            if (dialog != null) {
                dialog.setOnDismissListener {
                    removeFromManager(key)
                    if (key == PUSHDIALOG){
                        CacheUtils.savePushTipShoeRecord()
                    }
                    if (!stopShow) show()
//                    when(key){
//                        FREEORDER,SEARCHDIALOG->showFlag[key] = false
//                    }
                }
                dialog.show()
                return
            }
        }
    }
}